package feng.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import feng.common.BaseResponse;
import feng.common.ErrorCode;
import feng.common.ResultUtils;
import feng.entity.User;
import feng.service.UserService;
import feng.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fengzongpeng
 * @since 2023-07-31
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("list")
    public BaseResponse<List<User>> list(){
        List<User> userList = userService.list();
        return ResultUtils.success(userList);
    }

    @PostMapping("register")
    public BaseResponse register(@RequestBody User user){
        boolean save = userService.save(user);
        if (save){
            return ResultUtils.success("注册成功");
        }else {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
    }

    @GetMapping("page")
    public BaseResponse<PageInfo<User>> page(@RequestParam Integer page,@RequestParam Integer limit,@RequestParam String sort){
        PageHelper.startPage(page,limit,sort);
        List<User> userList = userService.list();
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return ResultUtils.success(pageInfo);
    }

    @GetMapping("login")
    public BaseResponse<HashMap<String,Object>> login(@RequestParam String userName, @RequestParam String passWord){
        User user = new User();
        user.setName(userName);
        user.setPassword(passWord);
        String token= TokenUtils.sign(user);
        HashMap<String,Object> hs=new HashMap<>();
        hs.put("token",token);
        return ResultUtils.success(hs);
    }
}

